package com.example.spring.demo.config.strategy;

import com.example.spring.demo.config.MyShardingUtil;
import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

import java.util.Collection;
import java.util.Objects;

/**
 * @author liangchao
 * 11/18/18 9:23 PM
 */
public class MyShardingDataSourceAlgorithm implements PreciseShardingAlgorithm<Integer> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
        String key = MyShardingUtil.getDataSourceKey(availableTargetNames.size(), shardingValue.getValue());
        for (String targetNames : availableTargetNames) {
            if (Objects.equals(key, targetNames)) {
                return key;
            }
        }
        return null;
    }
}
